<!-- 还款管理 -->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="姓名" prop="realName">
        <el-input v-model="queryParams.realName" placeholder="请输入用户姓名" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="资金方" prop="escrow">
        <el-input v-model="queryParams.escrow" placeholder="请输入资金方" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="还款状态" prop="refundStatus">
        <el-select v-model="queryParams.refundStatus" placeholder="还款状态" clearable style="width: 240px">
          <el-option v-for="dict in dict.type.cre_refund_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <el-table v-loading="loading" :data="creRefundList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="合同编号" prop="contractId" width="120" align="center" />
      <el-table-column label="用户手机号" prop="userPhone" :show-overflow-tooltip="true" width="150" align="center" />
      <el-table-column label="真实姓名" prop="realName" :show-overflow-tooltip="true" width="150" align="center" />
      <el-table-column label="资金方" prop="escrow" :show-overflow-tooltip="true" width="150" align="center" />
      <el-table-column label="贷款期数" prop="loanTerm" :show-overflow-tooltip="true" width="150" align="center" />
      <el-table-column label="还款方式" prop="paymentMethod" :show-overflow-tooltip="true" width="150" align="center" />
      <el-table-column label="贷款产品" prop="refundProduct" :show-overflow-tooltip="true" width="150" align="center" />
      <el-table-column label="月利率" prop="monthRate" :show-overflow-tooltip="true" width="150" align="center" />
      <el-table-column label="咨询费率" prop="consultingRate" :show-overflow-tooltip="true" width="150" align="center" />
      <el-table-column label="保证金费率" prop="marginRate" :show-overflow-tooltip="true" width="150" align="center" />
      <el-table-column label="应还总额" prop="shouldTotal" :show-overflow-tooltip="true" width="150" align="center" />
      <!-- <el-table-column label="应还日期" prop="refundDate" :show-overflow-tooltip="true" width="180" align="center" /> -->
      <el-table-column label="实还总额" prop="actualTotal" :show-overflow-tooltip="true" width="150" align="center" />
      <el-table-column label="实还日期" prop="actualDate" :show-overflow-tooltip="true" width="180" align="center" />
      <el-table-column label="还款状态" prop="refundStatus" :show-overflow-tooltip="true" width="150" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.refundStatus==0" style="color: blue;">未还款</span>
          <span v-else-if="scope.row.refundStatus==1" style="color: green;">已还款</span>
          <span v-else="scope.row.refundStatus==2" style="color: red;">已逾期</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" fixed="right">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleCollection(scope.row)">催收</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total"
      :page-sizes="[5, 10, 15, 20]"
      :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 催收 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-button type="primary" plain icon="el-icon-message" @click="email">发送邮件</el-button>
      <el-button type="primary" plain icon="el-icon-phone" @click="phone">电话催收</el-button>
      <el-button type="primary" plain icon="el-icon-user-solid" @click="TPC">第三方催收</el-button>
      <el-button type="danger" plain icon="el-icon-warning" @click="prosecution">起诉</el-button>
    </el-dialog>


    <!-- 添加或修改角色配置对话框 -->
    <!-- <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="合同编号" prop="contractId">
            <el-input v-model="form.contractId" placeholder="请输入合同编号" />
          </el-form-item>

          <el-form-item label="用户手机号" prop="userPhone">
            <el-input v-model="form.userPhone" placeholder="请输入用户手机号" />
          </el-form-item>

          <el-form-item label="用户真实姓名" prop="realName">
            <el-input v-model="form.realName" placeholder="请输入用户真实姓名" />
          </el-form-item>

          <el-form-item label="资金方" prop="escrow">
            <el-input v-model="form.escrow" placeholder="请输入资金方" />
          </el-form-item>

          <el-form-item label="贷款期数">
            <el-select v-model="form.loanTerm">
              <el-option
                v-for="dict in dict.type.cre_loan_term"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="还款方式">
            <el-select v-model="form.paymentMethod">
              <el-option
                v-for="dict in dict.type.cre_payment_method"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="贷款产品" prop="refundProduct">
            <el-input v-model="form.refundProduct" placeholder="请输入贷款产品" />
          </el-form-item>

          <el-form-item label="月利率" prop="monthRate">
            <el-input v-model="form.monthRate" placeholder="请输入月利率" />
          </el-form-item>
          <el-form-item label="咨询费率" prop="consultingRate">
            <el-input v-model="form.consultingRate" placeholder="请输入咨询费率" />
          </el-form-item>
          <el-form-item label="保证金费率" prop="marginRate">
            <el-input v-model="form.marginRate" placeholder="请输入保证金费率" />
          </el-form-item>

          <el-form-item label="应还金额" prop="shouldTotal">
            <el-input v-model="form.shouldTotal" placeholder="请输入应还金额" />
          </el-form-item>
          <el-form-item label="实还总额" prop="actualTotal">
            <el-input v-model="form.actualTotal" placeholder="请输入实还总额" />
          </el-form-item>
          
          <el-form-item label="还款状态">
            
            <el-select v-model="form.refundStatus" v-if="title=='添加合同'">
            <el-option  key="0"
                        label="未还款"
                        value="0"></el-option>
            </el-select>
            
            <el-select v-model="form.refundStatus" v-else-if="title=='修改合同'">
              <el-option
                v-for="dict in dict.type.cre_refund_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>

            </el-select>
          </el-form-item>

          <el-form-item label="备注">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog> -->

    <!-- 分配角色数据权限对话框 -->

  </div>
</template>

<script>
import { getRole, delRole, addRole, updateRole, dataScope, changeRoleStatus, deptTreeSelect } from "@/api/system/role";
import { findAll, checkEmailByUserId, sendEmail } from "@/api/credit/creRefund";

export default {
  name: "Role",
  dicts: ['cre_loan_term', 'sys_normal_disable', 'cre_payment_method', 'cre_refund_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 还款表格数据
      creRefundList: [],
      //还款数据
      refund: '',
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 5,
        realName: null,
        refundStatus: null,
        escrow: null,
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ],
        roleKey: [
          { required: true, message: "权限字符不能为空", trigger: "blur" }
        ],
        roleSort: [
          { required: true, message: "角色顺序不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询还款列表 */
    getList() {
      this.loading = true;
      findAll(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.creRefundList = response.rows;
        this.total = response.total;
        this.loading = false;
      }
      );
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        contractId: undefined,
        userPhone: undefined,
        realName: undefined,
        escrow: undefined,
        loanTerm: undefined,
        paymentMethod: undefined,
        refundProduct: undefined,
        monthRate: undefined,
        consultingRate: undefined,
        marginRate: undefined,
        shouldTotal: undefined,
        refundDate: undefined,
        actualTotal: undefined,
        actualDate: undefined,
        refundStatus: undefined,
        createTime: undefined,
        updateTime: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.roleId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },

    // /** 新增按钮操作 */
    // handleAdd() {
    //   this.reset();
    //   this.open = true;
    //   this.title = "添加合同";
    // },
    /** 催收按钮操作 */
    handleCollection(row) {
      this.reset();
      this.open = true;
      this.refund = row;
      this.title = "催收方式";
    },
    email() {
      checkEmailByUserId(this.refund.userId).then(res => {
        this.$confirm(this.refund.realName + '的邮箱为' + res + '，是否向其发送催收邮件？', '发送邮件', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          sendEmail(this.refund).then(res => {
            this.$message({
              type: 'success',
              message: '发送成功!',
            });
            this.open = false;
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消发送'
          });
        });
      })
    },
    phone(){
      this.$confirm('是否拨打'+this.refund.userPhone+'？', '拨打电话', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '正在拨打，请稍后...'
          });
          setTimeout(() => {
            window.location.href = 'tel://' + this.refund.userPhone
          }, 1000);
          this.open = false;
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消拨打'
          });          
        });

    },
    TPC(){
      const h = this.$createElement;
        this.$msgbox({
          title: '催收公司',
          message: h('p', null, [
            h('p',{ style: 'color: red' }, '是否要将'+this.refund.realName+'委托催收公司？合同号：'+this.refund.contractId)
          ]),
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true;
              instance.confirmButtonText = '正在将'+this.refund.realName+'的'+this.refund.contractId+'号合同发送给催收公司...';
              setTimeout(() => {
                done();
                setTimeout(() => {
                  instance.confirmButtonLoading = false;
                }, 300);
              }, 3000);
            } else {
              done();
            }
          }
        }).then(action => {
          this.$message({
            type: 'success',
            message: '发送成功！'
          });
          this.open = false;
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });
    },
    prosecution(){
      this.$confirm('该操作会向法院提起诉讼, 请谨慎操作！！', '起诉', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }).then(() => {
          this.$confirm('请再次确认是否要起诉'+this.refund.realName+'？', '确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '已收集相关材料，准备向法院发起诉讼'
          });       
        })
          
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消起诉'
          });          
        });

    },



    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.roleId != undefined) {
            this.form.menuIds = this.getMenuAllCheckedKeys();
            updateRole(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.menuIds = this.getMenuAllCheckedKeys();
            addRole(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 提交按钮（数据权限） */
    submitDataScope: function () {
      if (this.form.roleId != undefined) {
        this.form.deptIds = this.getDeptAllCheckedKeys();
        dataScope(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.openDataScope = false;
          this.getList();
        });
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.roleId || this.ids;
      this.$modal.confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？').then(function () {
        return delRole(roleIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('credit/refund/export', {
        ...this.queryParams
      }, `还款管理表_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>